package com.blue.base.shiro.filter;

import cn.hutool.http.HttpStatus;
import com.blue.base.common.exception.ShiroUnAuthorizedException;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 * @author liulei
 * @version 1.0
 */
@Slf4j
@AllArgsConstructor
public class RolesAuthFilter extends RolesAuthorizationFilter {

    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        String requestUrl = ((ShiroHttpServletRequest) request).getServletPath();
        Subject subject = SecurityUtils.getSubject();
        boolean permitted = subject.isPermitted(requestUrl);
        if (!subject.isAuthenticated()) {
            throw new ShiroUnAuthorizedException(HttpStatus.HTTP_UNAUTHORIZED, "认证失败，尚未登录");
        }
        if (!permitted) {
            throw new ShiroUnAuthorizedException(HttpStatus.HTTP_FORBIDDEN, "认证失败，无此类操作权限");
        }
        return true;
    }
}
